<?php
/**
 * 文件上传类
 *
 * @author YangZi <purocean@outlook.com>
 * @link https://github.com/purocean/
 * @copyright 2014-2015 <purocean@outlook.com>
 * @license http://www.apache.org/licenses/
 */

namespace Home\Lib;

class Uploader
{
    /**
     * 文件上传配置
     *
     * @var array
     */
    public $configs = array(
        'path' => './Upload/',
        'types' => [
            'image/gif' => '.gif',
            'image/jpg' => '.jpg',
            'image/jpeg' => '.jpg',
            'image/png' => '.png'
        ],
        'maxSize' => 512000, // 500 KiB
    );

    public function __construct($configs = array())
    {
        $this->configs = array_merge($this->configs, $configs);
    }

    /**
     * 执行上传.
     *
     * @param array $fileInfo 如 $_FILES['pic']
     *
     * @return array 上传结果
     */
    public function uplaod($fileInfo)
    {
        $result = array(
            'code' => 'error',
            'msg' => 'unkonw',
        );

        if ($fileInfo['error'] > 0) {
            $result['msg'] = $fileInfo['error'];
        } elseif ($fileInfo['size'] > $this->configs['maxSize']) {
            $result['msg'] = '文件过大！限制: '.round($this->configs['maxSize'] / 1024, 2).' KiB';
        } elseif (!array_key_exists($fileInfo['type'], $this->configs['types'])) {
            $result['msg'] = '文件类型错误: '.$fileInfo['type'];
        } else {
            $result['code'] = 'ok';
            $result['msg'] = '上传成功！文件大小: '.round($fileInfo['size'] / 1024, 2).' KiB';

            $filename = date('Y_m_d_H_i_s_').rand(0, 10000000).$this->configs['types'][$fileInfo['type']];
            if (file_exists($this->configs['path'].$filename)) {
                $result['msg'] = '请重新上传';
            } else {
                move_uploaded_file($fileInfo['tmp_name'], $this->configs['path'].$filename);
                $result['src'] = $this->configs['path'].$filename;
            }
        }

        return $result;
    }
}
